// pages/profile/advice/advice.js
Page({
  data: {
    // 当前选中的标签页
    activeTab: 'doctors',
    
    // 标签页配置
    tabs: [
      { key: 'doctors', name: '选择医生', icon: '👨‍⚕️' },
      { key: 'consultations', name: '我的咨询', icon: '💬' }
    ],
    
    // 医生列表
    doctors: [
      {
        id: 1,
        name: '王医生',
        title: '主任医师',
        department: '营养科',
        hospital: '市人民医院',
        avatar: '/assets/images/doctor-avatar.jpg',
        specialties: ['糖尿病管理', '高血压饮食', '减重指导'],
        experience: '15年',
        rating: 4.8,
        consultationCount: 1250,
        onlineStatus: 'online',
        responseTime: '5分钟内',
        consultationFee: 50,
        introduction: '专注于慢性病营养管理，擅长糖尿病、高血压等疾病的饮食指导。'
      },
      {
        id: 2,
        name: '李医生',
        title: '副主任医师',
        department: '内分泌科',
        hospital: '市中心医院',
        avatar: '/assets/images/doctor-avatar2.jpg',
        specialties: ['糖尿病', '甲状腺疾病', '代谢综合征'],
        experience: '12年',
        rating: 4.7,
        consultationCount: 980,
        onlineStatus: 'online',
        responseTime: '10分钟内',
        consultationFee: 45,
        introduction: '擅长糖尿病及其并发症的诊治，在血糖管理方面有丰富经验。'
      },
      {
        id: 3,
        name: '张医生',
        title: '主治医师',
        department: '心血管科',
        hospital: '市第一医院',
        avatar: '/assets/images/doctor-avatar3.jpg',
        specialties: ['高血压', '冠心病', '血脂异常'],
        experience: '8年',
        rating: 4.6,
        consultationCount: 650,
        onlineStatus: 'offline',
        responseTime: '30分钟内',
        consultationFee: 40,
        introduction: '专注于心血管疾病的预防和治疗，在高血压管理方面经验丰富。'
      }
    ],
    
    // 当前咨询列表
    consultations: [
      {
        id: 1,
        doctorId: 1,
        doctorName: '王医生',
        doctorAvatar: '/assets/images/doctor-avatar.jpg',
        title: '血糖管理咨询',
        status: 'active',
        lastMessage: '建议您减少精制碳水化合物的摄入',
        lastTime: '10:30',
        unreadCount: 1,
        startTime: '2024-01-15 09:00',
        messageCount: 8
      },
      {
        id: 2,
        doctorId: 2,
        doctorName: '李医生',
        doctorAvatar: '/assets/images/doctor-avatar2.jpg',
        title: '饮食调整咨询',
        status: 'completed',
        lastMessage: '谢谢医生的建议，我会按照您说的去做',
        lastTime: '昨天',
        unreadCount: 0,
        startTime: '2024-01-14 14:30',
        endTime: '2024-01-14 16:00',
        messageCount: 12
      }
    ],
    
    // 搜索关键词
    searchKeyword: '',
    
    // 筛选条件
    filterDepartment: '',
    filterStatus: '',
    
    // 选中的医生
    selectedDoctor: null,
    
    // 咨询表单
    consultationForm: {
      title: '',
      description: '',
      urgency: 'normal',
      attachments: []
    },
    
    // 显示状态
    showConsultationModal: false,
    showFilterModal: false
  },

  onLoad() {
    this.loadConsultations();
  },

  onShow() {
    this.loadConsultations();
  },

  // 加载咨询数据
  loadConsultations() {
    // 这里可以从服务器获取数据
    // 暂时使用模拟数据
  },

  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
  },

  // 搜索医生
  onSearchInput(e) {
    this.setData({ searchKeyword: e.detail.value });
  },

  // 选择医生
  selectDoctor(e) {
    const doctorId = e.currentTarget.dataset.id;
    const doctor = this.data.doctors.find(d => d.id === doctorId);
    this.setData({ 
      selectedDoctor: doctor,
      showConsultationModal: true 
    });
  },

  // 开始咨询
  startConsultation() {
    const { selectedDoctor } = this.data;
    
    // 创建咨询会话 - 状态为等待医生同意
    const newConsultation = {
      id: Date.now(),
      doctorId: selectedDoctor.id,
      doctorName: selectedDoctor.name,
      doctorAvatar: selectedDoctor.avatar,
      title: '咨询请求',
      status: 'waiting', // 等待医生同意
      lastMessage: '等待医生同意咨询...',
      lastTime: '刚刚',
      unreadCount: 0,
      startTime: this.formatTime(new Date()),
      messageCount: 0
    };

    this.setData({
      consultations: [newConsultation, ...this.data.consultations],
      showConsultationModal: false
    });

    wx.showToast({
      title: '咨询请求已发送，等待医生同意',
      icon: 'success'
    });

    // 不跳转到聊天页面，等待医生同意
  },

  // 继续咨询
  continueConsultation(e) {
    const consultationId = e.currentTarget.dataset.id;
    const consultation = this.data.consultations.find(c => c.id === consultationId);
    
    // 如果状态是等待同意，显示提示
    if (consultation.status === 'waiting') {
      wx.showToast({
        title: '等待医生同意咨询',
        icon: 'none'
      });
      return;
    }
    
    // 只有已同意的咨询才能进入聊天
    if (consultation.status === 'active' || consultation.status === 'completed') {
      wx.navigateTo({
        url: `/pages/profile/advice/chat/chat?doctorId=${consultation.doctorId}&consultationId=${consultationId}`
      });
    }
  },

  // 查看咨询详情
  viewConsultationDetail(e) {
    const consultationId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/profile/advice/detail/detail?id=${consultationId}`
    });
  },

  // 筛选医生
  filterDoctors() {
    this.setData({ showFilterModal: true });
  },

  // 应用筛选
  applyFilter(e) {
    const { department, status } = e.detail;
    this.setData({
      filterDepartment: department,
      filterStatus: status,
      showFilterModal: false
    });
  },

  // 清除筛选
  clearFilter() {
    this.setData({
      filterDepartment: '',
      filterStatus: '',
      searchKeyword: ''
    });
  },

  // 输入处理
  onFormInput(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;
    this.setData({
      [`consultationForm.${field}`]: value
    });
  },

  // 选择紧急程度
  selectUrgency(e) {
    const urgency = e.currentTarget.dataset.urgency;
    this.setData({
      'consultationForm.urgency': urgency
    });
  },

  // 添加附件
  addAttachment() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        const attachments = [...this.data.consultationForm.attachments, tempFilePath];
        this.setData({
          'consultationForm.attachments': attachments
        });
      }
    });
  },

  // 删除附件
  removeAttachment(e) {
    const index = e.currentTarget.dataset.index;
    const attachments = this.data.consultationForm.attachments;
    attachments.splice(index, 1);
    this.setData({
      'consultationForm.attachments': attachments
    });
  },

  // 取消咨询
  cancelConsultation() {
    this.setData({
      showConsultationModal: false,
      selectedDoctor: null,
      consultationForm: {
        title: '',
        description: '',
        urgency: 'normal',
        attachments: []
      }
    });
  },

  // 格式化时间
  formatTime(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();

    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
  },

  // 拨打电话
  callDoctor(e) {
    const doctorId = e.currentTarget.dataset.id;
    const doctor = this.data.doctors.find(d => d.id === doctorId);
    
    wx.showModal({
      title: '联系医生',
      content: `是否拨打${doctor.name}的电话？`,
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '400-xxx-xxxx', // 这里应该是医生的真实电话
            fail: () => {
              wx.showToast({
                title: '拨号失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  // 查看医生详情
  viewDoctorDetail(e) {
    const doctorId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/profile/advice/doctorDetail/doctorDetail?id=${doctorId}`
    });
  }
})